using System.Collections.Generic;
using BSDS.Commands.Commands.Implementation;
using BSDS.Core.Data.Local;
using BSDS.Core.Infrastructure.Logging;
using BSDS.Core.Model.Services;
using BSDS.Core.Model.Services.Jobs;
using BSDS.Core.Model.Services.Uploading;

namespace BSDS.Commands.Commands.Creation.Implementation
{
    public class UploadCommandCreator : CommandCreatorBase
    {
        private readonly UploadService uploadService;
        private readonly AccountService accountService;
        private readonly JobRepository jobRepository;
        private readonly JobService jobService;
        private readonly Logger logger;
        private readonly DataRepository dataRepository;

        public UploadCommandCreator(UploadService uploadService, AccountService accountService, JobRepository jobRepository, 
            JobService jobService, Logger logger, DataRepository dataRepository)
        {
            this.uploadService = uploadService;
            this.accountService = accountService;
            this.jobRepository = jobRepository;
            this.jobService = jobService;
            this.logger = logger;
            this.dataRepository = dataRepository;
        }

        protected override bool Supports(Dictionary<string, string> parameters)
        {
            return parameters.Count >= 3 && parameters.ContainsKey("upload") && parameters.ContainsKey("name") && parameters.ContainsKey("entity");
        }

        protected override ICommand Create(Dictionary<string, string> parameters)
        {
            var inputFilename = parameters["upload"];
            var dataSourceName = parameters["name"];
            var entityTypeName = parameters["entity"];

            DataFormat outputDataFormat = DataFormat.OriginalFormat;

            if (parameters.ContainsKey("toPipe"))
            {
                outputDataFormat = DataFormat.Pipe;
            }

            if (parameters.ContainsKey("toTab"))
            {
                outputDataFormat = DataFormat.Tab;
            }
            
            var queryKey = string.Empty;
            if (parameters.ContainsKey("queryKey"))
            {
                queryKey = parameters["queryKey"];
            }

            var dropFilenamePrefix = string.Empty;
            if (parameters.ContainsKey("dropFilenamePrefix"))
            {
                dropFilenamePrefix = parameters["dropFilenamePrefix"];
            }

            var config = new UploadCommandConfiguration(inputFilename, dataSourceName, outputDataFormat, entityTypeName, queryKey, dropFilenamePrefix);

            return new UploadCommand(uploadService, accountService, dataRepository, jobRepository, jobService, logger, config);
        }
    }
}